package com.zcxk.web.handler;

import com.zcxk.common.SingleResponse;
import com.zcxk.config.AuthToken;
import com.zcxk.constant.Constants;
import com.zcxk.ws.WSApp;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @author wangping
 * @date 2023-07-28 21:56
 */
public class CheckTokenHandler implements Handler<RoutingContext> {

  private final static Logger logger = LoggerFactory.getLogger(CheckTokenHandler.class);

  @Override
  public void handle(RoutingContext ctx) {
    HttpServerRequest request = ctx.request();
    String token = request.getHeader("token");
    Long userId = this.parseToken(token);
    if (Objects.isNull(userId)) {
      ctx.response().setStatusCode(HttpResponseStatus.UNAUTHORIZED.code())
        .setStatusMessage("check token failed")
        .end();
      return;
    }
    ctx.next();
  }

  private Long parseToken(String tokenStr) {
    try {
      if (tokenStr != null && !tokenStr.isEmpty()) {
        AuthToken token = AuthToken.fromSecureString(tokenStr, Constants.getSecretKey());
        if (!token.isExpired()) {
          return token.userId();
        }
      }
    } catch (IllegalArgumentException exception) {
      logger.error("parse token failed, happen IllegalArgumentException, token: {}", tokenStr, exception);
      return null;
    }
    return null;
  }
}
